package com.pb.service.boot.config;

import com.pb.infra.auth.service.LeadingOutService;
import com.pb.infra.oth.util.FileUtil;
import com.pb.infra.oth.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 开启定时任务，清空三天前的数据和文件夹及文件
 */

@Component
public class ScheduledTasks {

    @Autowired
    private LeadingOutService leadingOutService;

    /**
     * 要求6:00启定时任务
     */
    @Scheduled(cron = " 0 11 18 * * ?")
    public void deleteFieldTask() {
        Environment env = SpringContextUtil.getBean(Environment.class);
        String PATH = env.getProperty("file.path");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 此处每天只会执行一次，故每天清理一下三天之前的文件夹及文件
        Calendar ca = Calendar.getInstance();
        //设置时间为当前时间
        ca.setTime(new Date());
        ca.add(Calendar.DATE, - 0);
        Date lastMonth = ca.getTime();
        String beforeDate = format.format(lastMonth);
        String filePath = filenameFilter(PATH +  File.separator + beforeDate);
        File file = new File(filePath);
        if(file.exists()) {
            //删除目录下面所有文件
            FileUtil.deleteFile(new File(filePath));
            //删除空目录
            file.delete();
            //删除存储文件数据
            leadingOutService.deleteFile(filePath);
        }
    }

    /**
     * 路径遍历 漏洞修复
     * @param str
     * @return
     */
    public static String filenameFilter(String str){
        String strInjectListStr = "../|./|/..| |<|>|:|?";
        if(null != strInjectListStr && !"".equals(strInjectListStr)) {
            str = str.toLowerCase();
            String[] badStrs = strInjectListStr.split("\\|");
            for(int i = 0;i < badStrs.length;i++){
                if(str.indexOf(badStrs[i]) >= 0){
                    str = str.replace(badStrs[i],"");
                }
            }
        }
        return str;
    }
}
